<template>
  <view class="order-container">
    <view class="tabs">
      <view 
        v-for="(item, index) in tabs" 
        :key="index" 
        class="tab-item"
        :class="{ 'active': tabIndex === index }"
        @tap="switchTab(index)"
      >
        {{ item.name }}
      </view>
    </view>

    <view class="orders">
      <view v-if="filteredOrders.length === 0" class="empty">暂无订单</view>
      <view v-for="order in filteredOrders" :key="order.id" class="order-item card">
        <view @click="goToOrderDetails(order.id)">
          <view class="order-header">
            <view class="order-number">订单号：{{ order.ordernumber }}</view>
            <view class="order-status" :style="{ color: getOrderStatusColor(order.status) }">{{ order.status }}</view>
          </view>
          <view class="order-content">
            <image class="service-image" :src="order.img" mode="aspectFill"></image>
            <view class="service-info">
              <view class="service-name">{{ order.name }}</view>
              <view class="appointment-time">预约时间：{{ formatDateTime(order.appointment_time) }}</view>
			  <view class="appointment-time">截止时间：{{ formatDateTime(order.deadline) }}</view>
            </view>
          </view>
          <view class="order-details">
            <view class="order-time">下单时间：{{ formatDateTime(order.create_time) }}</view>
            <view class="order-amount">合计：￥{{ order.total_amount }}</view>
          </view>
        </view>
        <view class="order-actions">
          <view class="actions-container">
			   <view v-if="order.status === '待支付'" class="action sign-in" >去支付</view>
			   <view v-if="order.status === '退款中'" class="action sign-in" @tap="updateCancel(order)">取消退款</view>
			   <view v-if="order.status === '未签到'" class="action sign-in" @tap="handleReceive(order)">取消预约</view>
			   <view v-if="order.status === '已过期'" class="action sign-in" @tap="handleReceive(order)">申请退款</view>
            <view v-if="order.status === '未签到'" class="action sign-in">查看详情</view>
            <view v-else class="action view-details">查看详情</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      tabIndex: 0, // 当前激活的标签页索引
      tabs: [
        { id: 1, name: "全部订单" },
        { id: 2, name: "待支付" },
        { id: 3, name: "待签到" },
        { id: 4, name: "售后" },
		{ id: 5, name: "已过期" }
      ],
      orders: [], // 所有订单数据
      filteredOrders: [] // 根据标签页过滤后的订单数据
    };
  },
  onShow() {
    this.fetchOrders();
  },
  methods: {
    switchTab(index) {
      this.tabIndex = index;
      this.filteredOrders = this.filterOrdersByTab(this.tabs[index].name);
    },
    fetchOrders() {
      const token = uni.getStorageSync('Authorization');
      uni.request({
        url: 'http://localhost:8887/Serviceappointment/selectuser_id',
        method: 'GET',
        header: {
          'Authorization': token,
          'Content-Type': 'application/json'
        },
		
        success: (res) => {
          if (res.data.code === 200) {
            this.orders = res.data.data;
            this.filteredOrders = this.filterOrdersByTab(this.tabs[this.tabIndex].name);
          } else {
            uni.showToast({
              title: '获取订单失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          });
        }
      });
    },
    formatDateTime(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },
    getOrderStatusColor(status) {
      switch(status) {
        case '待支付':
          return 'orange';
        case '已签到':
          return 'green';
        case '未签到':
          return 'red';
        default:
          return '#666';
      }
    },
	handleReceive(order) {
	  this.updateOrderStatus(order, '退款中');
	},
	updateOrderStatus(order, newStatus) {
	  const token = uni.getStorageSync('Authorization');
	  uni.request({
	    url: 'http://localhost:8887/Serviceappointment/updatestatus',
	    method: 'POST',
	    header: {
	      'Authorization': token,
	      'Content-Type': 'application/json'
	    },
	    data: {
	      id: order.id,
	      status: newStatus
	    },
	    success: (res) => {
	      if (res.data.code === 200) {
	        this.fetchOrders(); 
	      } else {
	        uni.showToast({
	          title: '操作失败',
	          icon: 'none'
	        });
	      }
	    },
	    fail: () => {
	      uni.showToast({
	        title: '请求失败',
	        icon: 'none'
	      });
	    }
	  });
	},
	updateCancel(order){
		const token = uni.getStorageSync('Authorization');
		uni.request({
		  url: 'http://localhost:8887/Serviceappointment/updateCancel',
		  method: 'POST',
		  header: {
		    'Authorization': token,
		    'Content-Type': 'application/json'
		  },
		  data: {
		    id: order.id
		  },
		  success: (res) => {
		    if (res.data.code === 200 && res.data.data === '取消退款成功') {
		      uni.showToast({
		        title: '取消退款成功',
		        icon: 'success'
		      });
		      this.fetchOrders();
		    } else {
		      uni.showToast({
		        title: '操作失败',
		        icon: 'none'
		      });
		    }
		  },
		  fail: () => {
		    uni.showToast({
		      title: '请求失败',
		      icon: 'none'
		    });
		  }
		});
	},
    goToOrderDetails(orderId) {
      uni.navigateTo({
        url: `/pages/serviceorderdetails/serviceorderdetails?id=${orderId}`
      });
    },
    filterOrdersByTab(tabName) {
      let filtered = this.orders.filter(order => {
        if (tabName === "全部订单") {
          return true;
        } else if (tabName === "待支付") {
          return order.status === "待支付";
        } else if (tabName === "待签到") {
          return order.status === "未签到";
        } else if (tabName === "已过期") {
          return order.status === "已过期";
        } else if (tabName === "售后") {
          return ['退款中', '已退款'].includes(order.status);
        }
      });
      return filtered.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));
    }
  }
};
</script>
<style scoped>
.order-container {
  padding: 15px;
}
.tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}
.tab-item {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  font-size: 16px;
  cursor: pointer;
}
.tab-item.active {
  border-bottom: 2px solid #007aff;
  color: #007aff;
}
.orders {}
.order-item.card {
  background-color: #fff;
  margin-bottom: 15px;
  padding: 15px;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  position: relative;
}
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.order-number {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}
.order-status {
  font-size: 18px;
  font-weight: bold;
  white-space: nowrap;
}
.order-content {
  display: flex;
  margin-bottom: 10px;
}
.service-image {
  width: 100px;
  height: 100px;
  border-radius: 5px;
  margin-right: 10px;
  object-fit: cover;
}
.service-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.service-name {
  font-size: 20px;
  color: #333;
  font-weight: bold;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.appointment-time {
  font-size: 16px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.order-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  color: #666;
  border-top: 1px solid #eee; /* 添加边框 */
}
.order-time {
  font-size: 14px;
}
.order-amount {
  font-size: 18px;
  font-weight: bold;
}
.order-actions {
  position: absolute;
  bottom: 15px;
  right: 15px;
}
.actions-container {
  display: flex;
  align-items: center;
}
.action {
  padding: 5px 10px;
  margin-left: 10px;
  font-size: 14px;
  border: 1px solid #eee;
  border-radius: 5px;
}
.action:first-child {
  margin-left: 0;
}
.empty {
  text-align: center;
  color: #999;
  margin-top: 50rpx;
}
</style>